import jwt from 'jsonwebtoken';

export function sign(option: { id: number; username: string }) {
  return jwt.sign(option, 'lsy', {
    expiresIn: 86400, // 24小时过期
  });
}

export function verify() {
  return async (ctx, next) => {
    let token = ctx.request.headers.authorization;
    if (token) {
      // 校验
      try {
        const decoded = jwt.verify(token, 'lsy');
        if (decoded.id) {
          ctx.user_id = decoded.id;
          await next();
        }
      } catch (error) {
        ctx.body = {
          code: 401,
          data: null,
          message: 'token 过期',
        };
      }
    } else {
      ctx.body = {
        code: 401,
        data: null,
        message: 'token 不存在',
      };
    }
  };
}
